package cn.com.konyo.mis;

import java.io.File;
import java.io.FileFilter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;

import org.apache.commons.io.FileUtils;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;

public class GenerateFiles {
	
	public String basePath;
	
	public String generatePath;
	
	public String templatesPath;
	
	public String vmPath;
	
	
	
	
	/*public GenerateFiles() {
		super();
		Properties properties = new Properties();	
		properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,Constants.VM_PATH);
		properties.setProperty(Velocity.INPUT_ENCODING,Constants.ENCODING);
		properties.setProperty(Velocity.OUTPUT_ENCODING,Constants.ENCODING);
		Velocity.init(properties);
	}*/
	
	public GenerateFiles() {
		super();
	}
	
	public String init(String basePath,String modulename,String modulename_cn,String generateFileName){
		this.setBasePath(basePath);
		Properties properties = new Properties();	
		properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,this.getVmPath());
		properties.setProperty(Velocity.INPUT_ENCODING,Constants.ENCODING);
		properties.setProperty(Velocity.OUTPUT_ENCODING,Constants.ENCODING);
		Velocity.init(properties);
		
		File vmDir = new File(this.getVmPath());
		
		/*String modulename = "KUser";
		String modulename_cn = "用户";*/
		Map map = new HashMap();
		map.put("ModuleClass", modulename);
		map.put("moduleclass", modulename.toLowerCase());
		map.put("SESSION_CURRENTMODULE_ORDER_BY",   "$_SESSION[$currentModule.'_Sort_Order']");
		map.put("SESSION_CURRENTMODULE_SORT_ORDER", "$_SESSION[$currentModule.'_Order_By']");
		map.put("joinedTables", "$joinedTables");
		map.put("ModuleName", modulename);
		map.put("MODULENAME", modulename.toUpperCase());
		map.put("Module_Name", modulename_cn);
		
//		String uuid = UUID.randomUUID().toString();
		this.genFiles(modulename, vmDir, map,generateFileName);
		String bool = null;
		File generateFile = new File(this.getGeneratePath() + File.separator + generateFileName + ".zip");
		if(generateFile.exists() && generateFile.length() > 0){
			bool = generateFile.getName();
		}
		return bool;
	}
	
	private void genFiles(String modulename, File vmDir, Map map,String generateFileName) {
		try {
//			String uuid = generateFileName; //UUID.randomUUID().toString(); modulename
			File templatesDir = new File(this.getTemplatesPath());
			File templatesTPLDir = new File(templatesDir.getPath() + File.separator + "Smarty" + File.separator + "templates" + File.separator + "modules");
			
			File generateDir = new File(this.getGeneratePath() + File.separator + generateFileName);
			File generateTPLDir = new File(generateDir.getPath() + File.separator + "Smarty" + File.separator + "templates" + File.separator + "modules" + File.separator + modulename );
			File generatePHPDir = new File(generateDir.getPath() + File.separator + "modules" + File.separator + modulename );
			File generatePHPLangDir = new File(generatePHPDir.getPath()+File.separator+"language");
			
			/*System.err.println(templatesTPLDir.getPath());
			System.err.println(generatePHPDir.getPath());
			System.err.println(generatePHPLangDir.getPath());*/
			
			VelocityContext context = new VelocityContext();

			Iterator iterator = map.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry entity = (Entry) iterator.next();
				context.put(entity.getKey().toString(), entity
						.getValue().toString());
			}
			
			
			File[] vmFiles = vmDir.listFiles(new VMFileFilter());
			for (int i = 0; i < vmFiles.length; i++) {
				File vmFile = vmFiles[i];
				if (vmFile.isDirectory()) {
					continue;
				}
				String name = vmFile.getName();
				if (name.indexOf("ModuleClass") == 0) {
					name = modulename + name.substring(11);// 去除文件名中的 ModuleClass
				}
				name = name.substring(0, name.length() - 3);
				try {

					Template template = null;
					template = Velocity.getTemplate(vmFile.getName(),
							Constants.ENCODING);
					StringWriter sw = new StringWriter();
					template.merge(context, sw);

					File generate_PHP_JS_File = new File(generatePHPDir.getPath() + File.separator
							+ name);

					FileUtils.writeStringToFile(generate_PHP_JS_File, sw.toString());

				} catch (ResourceNotFoundException rnfe) {
					rnfe.printStackTrace();
				} catch (ParseErrorException pee) {
					pee.printStackTrace();
				} catch (MethodInvocationException mie) {
					mie.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			
			try {
				File[] all_PHP_JS_Files = vmDir.listFiles(new PHPJSFileFilter());
				for (int i = 0; i < all_PHP_JS_Files.length; i++) {
					FileUtils.copyFileToDirectory(all_PHP_JS_Files[i], generatePHPDir, true);
				}
				
				all_PHP_JS_Files = generatePHPDir.listFiles(new PHPJSFileFilter());
				for (int i = 0; i < all_PHP_JS_Files.length; i++) {
					File file = all_PHP_JS_Files[i];
					String name = file.getName();
					if (name.endsWith("lang.php")) {
						FileUtils.moveToDirectory(file, generatePHPLangDir,true);
					}
				}
				
				File[] tpl_Files = templatesTPLDir.listFiles(new TPLFileFilter());
				for (int i = 0; i < tpl_Files.length; i++) {
					FileUtils.copyFileToDirectory(tpl_Files[i], generateTPLDir, true);
				}
				
//				FileUtils.copyDirectoryToDirectory(templatesTPLDir, generateDir);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			File baseDir = new File(generateDir.getPath());
			File destFile = new File(generateDir.getPath()+".zip");
			Zip zip = new Zip();
			zip.setBasedir(baseDir);
			zip.setDestFile(destFile);
			Project p = new Project();
			p.setBaseDir(baseDir);
			zip.setProject(p);
			zip.execute();
			
			
			FileUtils.deleteDirectory(baseDir);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*public static void generate(String modulename,String modulename_cn) {
		try {
			GenerateFiles gf = new GenerateFiles();
			File vmDir = new File(Constants.VM_PATH);
			
			String modulename = "KUser";
			String modulename_cn = "用户";
			Map map = new HashMap();
			map.put("ModuleClass", modulename);
			map.put("moduleclass", modulename.toLowerCase());
			map.put("SESSION_CURRENTMODULE_ORDER_BY",   "$_SESSION[$currentModule.'_Sort_Order']");
			map.put("SESSION_CURRENTMODULE_SORT_ORDER", "$_SESSION[$currentModule.'_Order_By']");
			map.put("joinedTables", "$joinedTables");
			map.put("ModuleName", modulename);
			map.put("MODULENAME", modulename.toUpperCase());
			map.put("Module_Name", modulename_cn);

			gf.writeVMFiles(modulename, vmDir, map);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}*/
	
	/*private void writeVMFiles(String modulename, File vmDir, Map map) {
	try {
		String uuid = modulename; //UUID.randomUUID().toString();
		File templatesDir = new File(Constants.TEMPLATES_PATH);
		File templatesTPLDir = new File(templatesDir.getPath() + File.separator + "Smarty");
		
		File generateDir = new File(Constants.GENERATE_PATH + File.separator + uuid);
		File generatePHPDir = new File(generateDir.getPath() + File.separator + "modules" + File.separator + modulename );
		File generatePHPLangDir = new File(generatePHPDir.getPath()+File.separator+"language");
		
		VelocityContext context = new VelocityContext();

		Iterator iterator = map.entrySet().iterator();
		while (iterator.hasNext()) {
			Entry entity = (Entry) iterator.next();
			context.put(entity.getKey().toString(), entity
					.getValue().toString());
		}
		
		
		File[] vmFiles = vmDir.listFiles(new VMFileFilter());
		for (int i = 0; i < vmFiles.length; i++) {
			File vmFile = vmFiles[i];
			if (vmFile.isDirectory()) {
				continue;
			}
			String name = vmFile.getName();
			if (name.indexOf("ModuleClass") == 0) {
				name = modulename + name.substring(11);// 去除文件名中的 ModuleClass
			}
			name = name.substring(0, name.length() - 3);
			try {

				Template template = null;
				template = Velocity.getTemplate(vmFile.getName(),
						Constants.ENCODING);
				StringWriter sw = new StringWriter();
				template.merge(context, sw);

				File generate_PHP_JS_File = new File(generatePHPDir.getPath() + File.separator
						+ name);

				FileUtils.writeStringToFile(generate_PHP_JS_File, sw.toString());

			} catch (ResourceNotFoundException rnfe) {
				rnfe.printStackTrace();
			} catch (ParseErrorException pee) {
				pee.printStackTrace();
			} catch (MethodInvocationException mie) {
				mie.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		
		try {
			File[] all_PHP_JS_Files = vmDir.listFiles(new PHPJSFileFilter());
			for (int i = 0; i < all_PHP_JS_Files.length; i++) {
				FileUtils.copyFileToDirectory(all_PHP_JS_Files[i], generatePHPDir, true);
			}
			
			all_PHP_JS_Files = generatePHPDir.listFiles(new PHPJSFileFilter());
			for (int i = 0; i < all_PHP_JS_Files.length; i++) {
				File file = all_PHP_JS_Files[i];
				String name = file.getName();
				if (name.endsWith("lang.php")) {
					FileUtils.moveToDirectory(file, generatePHPLangDir,true);
				}
			}
			
			FileUtils.copyDirectoryToDirectory(templatesTPLDir, generateDir);
		} catch (Exception e) {
			e.printStackTrace();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
}
*/
	
	
	
	public String getBasePath() {
		return basePath;
	}

	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}

	public String getGeneratePath() {
		return getBasePath() + "/generateFiles";
	}

	public void setGeneratePath(String generatePath) {
		this.generatePath = generatePath;
	}

	public String getTemplatesPath() {
		return getBasePath() + "/templates";
	}

	public void setTemplatesPath(String templatesPath) {
		this.templatesPath = templatesPath;
	}

	public String getVmPath() {
		return getBasePath() + "/templates/modules";
	}

	public void setVmPath(String vmPath) {
		this.vmPath = vmPath;
	}

	
}

class VMFileFilter implements FileFilter {
	public boolean accept(File file) {
		String name = file.getName();
		boolean phpfile = false;
		if (name.toLowerCase().endsWith(".vm")) {
			phpfile = true;
		}
		return phpfile;
	}
}

class TPLFileFilter implements FileFilter {
	public boolean accept(File file) {
		String name = file.getName();
		boolean tplfile = false;
		if (name.toLowerCase().endsWith(".tpl")) {
			tplfile = true;
		}
		return tplfile;
	}
}

class PHPJSFileFilter implements FileFilter {
	public boolean accept(File file) {
		String name = file.getName();
		boolean phpfile = false;
		if (name.toLowerCase().endsWith(".php") || name.toLowerCase().endsWith(".js")) {
			phpfile = true;
		}
		return phpfile;
	}
}

